<template>
  <view class="">
    <!-- 搜索输入框 -->
    <view class="search-input-wrap">
      <view class="icon-search">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="11" cy="11" r="8"></circle>
          <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
        </svg>
      </view>
      <input 
        class="search-input" 
        type="text" 
        placeholder="搜索位置、无障碍设施、景点..." 
        v-model="keyword"
        @input="handleInput"
        @confirm="searchPOI"
      />
      <view class="clear-btn" v-if="keyword" @click="clearSearch">
        <text class="iconfont icon-close"></text>
      </view>
    </view>

    <!-- 搜索结果列表 -->
    <scroll-view 
      scroll-y 
      class="search-results" 
      v-if="showResults && searchResults.length > 0">
      <view 
        class="result-item" 
        v-for="(item, index) in searchResults" 
        :key="index"
        @click="selectPOI(item)"
      >
        <view class="item-icon">
          <text class="iconfont" :class="getIconClass(item.type)"></text>
        </view>
        <view class="item-content">
          <text class="item-name">{{ item.name }}</text>
          <text class="item-address">{{ item.address }}</text>
        </view>
        <view class="item-distance" v-if="item.distance">
          {{ formatDistance(item.distance) }}
        </view>
      </view>
    </scroll-view>
    
    <!-- 无搜索结果提示 -->
    <view class="no-results" v-if="showResults && searchResults.length === 0 && keyword">
      <text class="no-results-text">未找到相关结果</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';

// 定义props
const props = defineProps({
  // 可以接收外部传入的自定义POI数据
  customPOIs: {
    type: Array,
    default: () => []
  }
});

// 定义事件
const emit = defineEmits(['select-poi', 'search-complete']);

// 搜索关键词
const keyword = ref('');
// 搜索结果
const searchResults = ref([]);
// 是否显示结果列表
const showResults = ref(false);
// 搜索状态
const isSearching = ref(false);
// 定时器，用于实现防抖
let searchTimer = null;

// 获取POI图标类
function getIconClass(type) {
  const iconMap = {
    'facility': 'icon-facility',
    'restaurant': 'icon-restaurant',
    'hotel': 'icon-hotel',
    'shopping': 'icon-shop',
    'entertainment': 'icon-entertainment',
    'hospital': 'icon-hospital',
    'default': 'icon-marker'
  };
  
  return iconMap[type] || iconMap.default;
}

// 格式化距离
function formatDistance(distance) {
  if (distance >= 1000) {
    return (distance / 1000).toFixed(1) + 'km';
  }
  return distance + 'm';
}

// 输入事件处理
function handleInput() {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  // 防抖处理，300ms后执行搜索
  searchTimer = setTimeout(() => {
    if (keyword.value.trim()) {
      searchPOI();
    } else {
      clearResults();
    }
  }, 300);
}

// 清空搜索
function clearSearch() {
  keyword.value = '';
  clearResults();
}

// 清空结果
function clearResults() {
  searchResults.value = [];
  showResults.value = false;
}

// 搜索POI
async function searchPOI() {
  if (!keyword.value.trim() || isSearching.value) return;
  
  isSearching.value = true;
  
  try {
    if (!window.AMap) {
      throw new Error('地图API未加载');
    }
    
    // 创建搜索插件实例
    const placeSearch = new window.AMap.PlaceSearch({
      city: '全国', // 全国范围搜索
      pageSize: 10,  // 每页结果数
      pageIndex: 1   // 页码
    });
    
    // 异步搜索
    placeSearch.search(keyword.value, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        // 处理官方POI搜索结果
        const officialResults = result.poiList.pois.map(poi => ({
          id: poi.id,
          name: poi.name,
          address: poi.address || '未知地址',
          location: {
            lng: poi.location.lng,
            lat: poi.location.lat
          },
          type: getPoiType(poi.type),
          distance: poi.distance,
          isOfficial: true
        }));
        
        // 处理自定义POI，使用关键词过滤
        const customResults = props.customPOIs
          .filter(poi => 
            poi.name.includes(keyword.value) || 
            (poi.address && poi.address.includes(keyword.value))
          )
          .map(poi => ({
            ...poi,
            isCustom: true
          }));
        
        // 合并搜索结果
        searchResults.value = [...officialResults, ...customResults];
        showResults.value = true;
        
        // 发送搜索完成事件
        emit('search-complete', searchResults.value);
      } else {
        // 仅显示自定义POI
        const customResults = props.customPOIs
          .filter(poi => 
            poi.name.includes(keyword.value) || 
            (poi.address && poi.address.includes(keyword.value))
          )
          .map(poi => ({
            ...poi,
            isCustom: true
          }));
        
        searchResults.value = customResults;
        showResults.value = true;
        console.error('官方POI搜索失败:', status, result);
        
        // 发送搜索完成事件
        emit('search-complete', searchResults.value);
      }
      
      isSearching.value = false;
    });
  } catch (error) {
    console.error('搜索出错:', error);
    isSearching.value = false;
    
    // 使用自定义POI作为备选
    const customResults = props.customPOIs
      .filter(poi => 
        poi.name.includes(keyword.value) || 
        (poi.address && poi.address.includes(keyword.value))
      )
      .map(poi => ({
        ...poi,
        isCustom: true
      }));
    
    searchResults.value = customResults;
    showResults.value = true;
    
    uni.showToast({
      title: '搜索服务异常',
      icon: 'none'
    });
  }
}

// 根据POI类型获取分类
function getPoiType(typeCode) {
  // 简化分类处理
  if (!typeCode) return 'default';
  
  if (typeCode.includes('餐饮')) return 'restaurant';
  if (typeCode.includes('购物')) return 'shopping';
  if (typeCode.includes('医疗')) return 'hospital';
  if (typeCode.includes('酒店')) return 'hotel';
  if (typeCode.includes('娱乐')) return 'entertainment';
  
  return 'default';
}

// 选择POI
function selectPOI(poi) {
  emit('select-poi', poi);
  showResults.value = false;
}

// 监听自定义POI变化
watch(() => props.customPOIs, (newVal) => {
  // 如果正在搜索且有关键词，重新搜索包含新的自定义POI
  if (keyword.value.trim()) {
    searchPOI();
  }
}, { deep: true });
</script>

<style scoped>
.poi-search-container {
  position: relative;
  width: 100%;
  z-index: 100;
  background: rgba(255, 255, 255, 0.9);
}

.search-input-wrap {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, rgba(75, 137, 253, 0.18), rgba(63, 123, 252, 0.1));
  padding: 5rpx 30rpx;
  border-radius: 50rpx;
  box-shadow: 0 6rpx 20rpx rgba(63, 123, 252, 0.15);
  margin: 30rpx 25rpx;
  border: 1px solid rgba(63, 123, 252, 0.25);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  transform: translateY(0);
  transition: all 0.3s ease;
}

.search-input-wrap:active {
  transform: translateY(2rpx);
  box-shadow: 0 3rpx 10rpx rgba(63, 123, 252, 0.1);
}

.icon-search {
  margin-right: 20rpx;
  color: #3F7BFC;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-search svg {
  width: 40rpx;
  height: 40rpx;
  opacity: 0.9;
}

.search-input {
  flex: 1;
  height: 72rpx;
  font-size: 30rpx;
  color: #333;
  background: transparent;
}

.search-input::placeholder {
  color: rgba(63, 123, 252, 0.6);
  font-weight: 300;
}

.clear-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #3F7BFC;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.clear-btn:active {
  opacity: 1;
}

.search-results {
  position: absolute;
  top: 100rpx;
  left: 20rpx;
  right: 20rpx;
  max-height: 600rpx;
  background-color: rgba(255, 255, 255, 0.98);
  border-radius: 20rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  z-index: 101;
  border: 1px solid rgba(63, 123, 252, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  overflow: hidden;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  transition: background-color 0.2s ease;
}

.result-item:active {
  background-color: rgba(63, 123, 252, 0.05);
}

.result-item:last-child {
  border-bottom: none;
}

.item-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
  color: #3F7BFC;
}

.item-content {
  flex: 1;
  overflow: hidden;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.item-address {
  font-size: 24rpx;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-distance {
  font-size: 24rpx;
  color: #3F7BFC;
  margin-left: 20rpx;
}

.no-results {
  position: absolute;
  top: 100rpx;
  left: 20rpx;
  right: 20rpx;
  background-color: rgba(255, 255, 255, 0.98);
  border-radius: 20rpx;
  padding: 40rpx 0;
  text-align: center;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  z-index: 101;
  border: 1px solid rgba(63, 123, 252, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.no-results-text {
  font-size: 28rpx;
  color: #999;
}
</style> 